<template>
    <div>
        <div class="section">
            <div class="location">
                <span>当前位置：</span>
                <a href="/index.html">首页</a> &gt;
                <a href="/cart.html">购物车</a>
            </div>
        </div>

        <div class="section">
            <div class="wrapper">
                <div class="bg-wrap">
                    <!--购物车头部-->
                    <div class="cart-head clearfix">
                        <h2>
                            <i class="iconfont icon-cart"></i>我的购物车</h2>
                        <div class="cart-setp">
                            <ul>
                                <li class="first active">
                                    <div class="progress">
                                        <span>1</span>
                                        放进购物车
                                    </div>
                                </li>
                                <li>
                                    <div class="progress">
                                        <span>2</span>
                                        填写订单信息
                                    </div>
                                </li>
                                <li class="last">
                                    <div class="progress">
                                        <span>3</span>
                                        支付/确认订单
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!--购物车头部-->
                    <!--商品列表-->
                    <div class="cart-box">
                        <input id="jsondata" name="jsondata" type="hidden">
                        <table width="100%" align="center" class="cart-table" border="0" cellspacing="0" cellpadding="8">
                            <tbody>
                                <tr>
                                    <th width="60" align="center">
                                        <a href="javascript:void(0)" @click="selectAll">全选/反选</a>
                                        <!-- <el-button @click="selectAll" size="mini" type="primary">全选/反选</el-button> -->
                                        <!-- <el-checkbox @change="handleCheckAllChange" v-model="isSelectedAll"></el-checkbox> -->
                                    </th>
                                    <th align="left" colspan="2">商品信息</th>
                                    <th width="84" align="left">单价</th>
                                    <th width="104" align="center">数量</th>
                                    <th width="104" align="left">金额(元)</th>
                                    <th width="54" align="center">操作</th>
                                </tr>
                                <tr v-for="(item,index) in goodsList" :key="item.id">
                                    <td width="48" align="center">
                                        <!-- <el-checkbox v-model="item.isSelected"  @change="handleEveryCheckChange"></el-checkbox> -->
                                        <el-switch v-model="item.isSelected" active-color="#0094ff" inactive-color="#333333">
                                        </el-switch>
                                    </td>
                                    <td align="left" colspan="2">
                                        <div style="display:flex;">
                                            <img width="50" style="margin-left:15px;" height="50" :src="item.img_url" alt="">
                                            <span style="line-height:50px;margin-left:15px;">
                                                {{item.title}}
                                            </span>
                                        </div>
                                    </td>
                                    <td width="84" align="left">{{item.sell_price}}</td>
                                    <td width="104" align="center">
                                        <subnumber @goodsNumberChange="getGoodsNumberChange" :goodsId="item.id" :initCount="item.buycount"></subnumber>
                                    </td>
                                    <td width="104" align="left">{{item.sell_price*item.buycount}}</td>
                                    <td width="54" align="center">
                                        <a href="javascript:void(0)" @click="delGoods(item.id,index)">删 除</a>
                                    </td>
                                </tr>
                                <tr v-if="goodsList.length<=0">
                                    <td colspan="10">
                                        <div class="msg-tips">
                                            <div class="icon warning">
                                                <i class="iconfont icon-tip"></i>
                                            </div>
                                            <div class="info">
                                                <strong>购物车没有商品！</strong>
                                                <p>您的购物车为空，
                                                    <a href="/index.html">马上去购物</a>吧！</p>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th align="right" colspan="8">
                                        已选择商品
                                        <b class="red" id="totalQuantity">{{getTotalCount}}</b> 件 &nbsp;&nbsp;&nbsp; 商品总金额（不含运费）：
                                        <span class="red">￥</span>
                                        <b class="red" id="totalAmount">{{getTotalAmount}}</b>元
                                    </th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <!--/商品列表-->
                    <!--购物车底部-->
                    <div class="cart-foot clearfix">
                        <div class="right-box">
                            <button class="button" onclick="javascript:location.href='/index.html';">继续购物</button>
                            <button class="submit" @click="goToOrder">立即结算</button>
                        </div>
                    </div>
                    <!--购物车底部-->
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
</style>

<script>
    //导入subnumber子组件
    import subnumber from '../subcomponent/subnumber.vue'

    import {getGoodsObj} from '../../common/localStorageHelper.js'

    export default {
        data() {
            return {
                goodsList: [],
                isSelectedAll: true
            }
        },
        created() {
            this.getGoodsListData()
        },
        computed: {
            //计算总数量
            getTotalCount() {
                let totalCount = 0

                this.goodsList.forEach(item => {
                    if (item.isSelected) {
                        totalCount += item.buycount
                    }
                })

                return totalCount
            },
            //计算总金额
            getTotalAmount() {
                let totalAmount = 0

                this.goodsList.forEach(item => {
                    if (item.isSelected) {
                        totalAmount += item.sell_price * item.buycount
                    }
                })

                return totalAmount
            }
        },
        components: {
            subnumber
        },
        methods: {
            getGoodsListData() {
                //1.获取原先保存在localStorage中的数据
                const localGoods = getGoodsObj()

                if (JSON.stringify(localGoods) == "{}") {
                    console.log("---xxxxx----")
                    return
                }

                //2.获取ids
                let idsArray = []
                for (const key in localGoods) {
                    idsArray.push(key)
                }

                if (idsArray.length <= 0) return

                //3.根据url发送请求
                const url = `site/comment/getshopcargoods/${idsArray.join(',')}`

                this.$axios.get(url).then(response => {
                    response.data.message.forEach(item => {
                        item.buycount = localGoods[item.id]
                        item.isSelected = true
                    })

                    this.goodsList = response.data.message
                })
            },
            //全选/反选
            handleCheckAllChange(isSelected) {
                this.goodsList.forEach(item => {
                    item.isSelected = isSelected
                })
            },
            //选择每一个
            handleEveryCheckChange() {
                let isSelectAll = false

                this.goodsList.forEach(item => {
                    if (item.isSelected) {
                        isSelectAll = true
                    }
                })

                this.isSelectedAll = isSelectAll
            },
            //按钮的全选与反选
            selectAll() {
                this.isSelectedAll = !this.isSelectedAll

                this.goodsList.forEach(item => {
                    item.isSelected = this.isSelectedAll
                })
            },
            //商品数量变化了
            getGoodsNumberChange(goods) {
                //更新this.goodsList中的数据
                this.goodsList.forEach(item => {
                    if (item.id === goods.goodsId) {
                        item.buycount = goods.count
                    }
                })

                //调用vuex的方法来进行更新
                this.$store.commit('updateGoods', goods)
            },
            //删除商品
            delGoods(goodsId, index) {
                this.$confirm('确认删除该商品吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //删除vuex及localstorage中的值
                    this.$store.commit('deleteGoodsById',goodsId)

                    //删除goodsList中的数据
                    this.goodsList.splice(index,1)
                }).catch(() => {
                    
                });
            },
            //下单操作
            goToOrder(){
                //获取选中的订单
                let ids = []
                this.goodsList.forEach(item=>{
                    if(item.isSelected){
                        ids.push(item.id)
                    }
                })
                
                if(ids.length<=0){
                    this.$message.error("请至少选择一件商品")
                    return
                }

                this.$router.push({path:`/site/order/${ids.join(',')}`})
            }
        }
    }
</script>